var main = "#content";

var LayoutContent = {
    layout: -1,
    ensurePointSelection: function(force) {
        if (this.layout !== 1 || force === true) {
            $(main).html($.render.pointSelection(LayoutUserPanel));
            LayoutPointSelection.init();
            this.layout = 1;
        }
    },
    isPointLayout: function() {
        return this.layout === 1;
    },
    ensureSubjectSelection: function(force) {
        if (this.layout !== 2 || force === true) {
            $(main).html($.render.subjectSelection(LayoutSubjects));
            LayoutSubjects.init();
            this.layout = 2;
        }
    },
    ensureResultView: function(force) {
        if (this.layout !== 3 || force === true) {
            var sum = 0;
            var nbr = 0;
            var max = 0;
            var min = 99999;
            var ups = LayoutUserPanel.usersPoints;
            for (var user in ups) {
                if (ups.hasOwnProperty(user)) {
                    var p = ups[user];
                    nbr += 1;
                    sum += p;
                    max = Math.max(max, p);
                    min = Math.min(min, p);

                }
            }
            var avg = Math.round(sum / nbr);

            if (nbr > 0) {
                var html = "";
                html += "<h1>Result</h1>";
                html += "<center><h2>" + LayoutSubjects.getSubject().title + "</h2></center>";

                for (var user in ups) {
                    if (user && ups.hasOwnProperty(user)) {
                        var p = ups[user];
                        html += "<h2>" + user + ":" + p + "</h2>";
                    }
                }

                html += "<h2>Max:{0} Min:{1} Avg:{2}</h2>";
                html += "<div class='button small-button' id='accept'>Accept</div>";
                html += "<div class='button small-button' id='restart'>Rerun</div>";
                $(main).html(html.format(max, min, avg));

                $("#restart").click(function() {
                    LayoutUserPanel.reset();
                });
                $("#accept").click(function() {
                    LayoutSubjects.setSubjectResult(avg);
                    $("#panel .summary").click();
                });

            } else {
                $(main).html("<h1>Nothing to see yet!</h1>");
            }
            this.layout = 3;
        }
    },
    init: function() {
        this.ensureSubjectSelection();
    }
};

var LayoutSubjects = {
    subjects: [
        {title: "No subject added!", selected: "disabledbutton"}
    ],
    subject_idx: -1,
    total: "Please rate all subjects first!",
    init: function() {
        $(".subject").click(function() {
            if(LayoutSubjects.hasNoSubject()){
                return;
            }
            if(LayoutUserPanel.isNoUsers()){
                alert("There are no users!");
                return;
            }
            
            var subject = $(this).attr("data");
            var subs = LayoutSubjects.subjects;
            for (var i = 0; i < subs.length; i++) {
                subs.selected = "";
                if (subs[i].title === subject) {
                    LayoutSubjects.setSubjectIdx(i);
                    LayoutUserPanel.reset();
                }
            }
        });

        $(".addsubject").click(function() {
            LayoutSubjects.addSubject();
        });
    },
    addSubject: function() {
        var title = prompt("Please enter your title", "MyFeature X");
        if (title !== null && title !== "") {
            if (this.hasNoSubject()) {
                this.subjects.pop();
            }
            this.subjects.push({title: title});
            this.init();
            LayoutContent.ensureSubjectSelection(true);
        }
    },
    setSubjectIdx: function(i) {
        if (this.subject_idx > -1) {
            this.subjects[this.subject_idx].selected = "";
        }
        $("#subject_current").text(this.subjects[i].title);
        this.subject_idx = i;
        this.subjects[i].selected = "selected";
    },
            
    setSubjectResult: function(value) {
        this.subjects[this.subject_idx].sum = value;

        var tot = 0;
        for (var i = 0; i < this.subjects.length; i++) {
            var s = this.subjects[i];
            if (!s.sum) {
                return;
            } else {
                tot += s.sum;
            }
        }
        var text = tot*8 + " man-hours";
        var week = tot / 5;
        var month = tot / 20;
        var year = tot / 220;

        text += " = " + tot + " man-days";
        text += " = " + week + " man-weeks";
        text += " = " + month + " man-months";
        text += " = " + year + " man-years";
        
        this.total = text;
    },
    getSubject: function() {
        return this.subject_idx > -1 ? this.subjects[this.subject_idx] : false;
    },
    hasNoSubject: function (){
        return this.subjects.length === 1 && this.subjects[0].title === "No subject added!";
    }
};

var LayoutPointSelection = {
    points: [1, 2, 3, 5, 8, 13, 20, 40, 60, 80, 100],
    point_idx: -1,
    listener_bound: false,
    init: function() {

        if (!this.listener_bound) {
            $(main).bind("touchstart", this.onTouch, true);
            $(main).click(this.onTap);
            $(document).keydown(this.onKey);
            this.listener_bound = true;
        }

        //this.pointIncrement();
    },
    showTitle: function(msg) {
        if (msg) {
            $("#content .title").text(msg);
        } else {
            $("#content .title").text("Planning Poker");
        }
    },
    onTouch: function(e) {
        if (!LayoutContent.isPointLayout())
            return;
        e = e || window.event;
        var x = e.pageX || e.touches[0].pageX;

        if (x >= $(main).outerWidth() * 0.5) {
            LayoutPointSelection.pointIncrement();
        } else {
            LayoutPointSelection.pointDecrement();
        }

        if (LayoutUserPanel.current) {
            LayoutUserPanel.setCurrentUserPoints(LayoutPointSelection.pointGet());
        }
        e.preventDefault();
    },
    onTap: function(e) {
        if (!LayoutContent.isPointLayout())
            return;
        e = e || window.event;

        var x = e.pageX || e.clientX;

        if (x >= $(main).outerWidth() * 0.5) {
            LayoutPointSelection.pointIncrement();
        } else {
            LayoutPointSelection.pointDecrement();
        }

        if (LayoutUserPanel.current) {
            LayoutUserPanel.setCurrentUserPoints(LayoutPointSelection.pointGet());
        }
        e.preventDefault();
    },
    evt: undefined,
    onKey: function(e) {
        if (!LayoutContent.isPointLayout())
            return;
        e = e || window.event; //Catch both
        if (this.evt && e.timeStamp === this.evt.timeStamp) { // DOM-tree trigger two times
            return;
        }
        this.evt = e;

        if (e.keyCode === 37) { // left arrow
            LayoutPointSelection.pointDecrement();
        }
        if (e.keyCode === 39) { // right arrow
            LayoutPointSelection.pointIncrement();
        }
        if (e.keyCode === 32) { // space
            LayoutUserPanel.nextUser();
        }
        if (LayoutUserPanel.current) {
            LayoutUserPanel.setCurrentUserPoints(LayoutPointSelection.pointGet());
        }
    },
    pointSet: function(value) {

        for (var i = 0; i < this.points.length; i++) {
            if (value === this.points[i]) {
                this.point_idx = i;
                break;
            }
        }

        $("#point").html(this.points[this.point_idx]);
    },
    pointIncrement: function() {
        this.point_idx = (this.point_idx >= this.points.length - 1) ? 0 : this.point_idx + 1;
        $("#point").html(this.points[this.point_idx]);
    },
    pointDecrement: function() {
        this.point_idx = (this.point_idx <= 0) ? this.points.length - 1 : this.point_idx - 1;
        $("#point").html(this.points[this.point_idx]);
    },
    pointReset: function() {
        this.point_idx = -1;
        $("#point").html("X");
    },
    pointGet: function() {
        return this.points[this.point_idx];
    }
};



var LayoutUserPanel = {
    current: "",
    users: [
        {name: "Please add users!", selected: "disabledbutton"}
    ],
    usersPoints: {
        //Eve:2
        //Roland:3
    },
    init: function() {
        this.current = this.users[0].name;
        //LayoutPointSelection.showTitle(this.current);
        $("#panel").html($.render.userButtons(this));

        $("#panel .summary").click(function() {
            LayoutUserPanel.current = false;
            LayoutContent.ensureSubjectSelection();
            $("#panel .button").removeClass("selected");
            $(this).addClass("selected");
        });

        $("#panel .user").click(function(e) {
            if (!LayoutSubjects.getSubject())
                return;

            var usr = LayoutUserPanel.current = $(this).attr("data");
            //LayoutPointSelection.showTitle(usr);
            LayoutContent.ensurePointSelection();

            LayoutPointSelection.pointReset();
            if (LayoutUserPanel.usersPoints.hasOwnProperty(usr)) {
                LayoutPointSelection.pointSet(LayoutUserPanel.usersPoints[usr]);
            }

            $("#panel .button").removeClass("selected");
            $(this).addClass("selected");
        });

        $("#panel .result").click(function() {
            if (!LayoutSubjects.getSubject())
                return;
            LayoutUserPanel.current = false;
            LayoutContent.ensureResultView();
            $("#panel .button").removeClass("selected");
            $(this).addClass("selected");
        });

        $("#panel .adduser").click(function(e) {
            LayoutUserPanel.current = false;
            var name = prompt("Please enter your name", "Alice");
            if (name !== null && name !== "") {
                if(LayoutUserPanel.isNoUsers()){
                    LayoutUserPanel.users.pop();
                }
                LayoutUserPanel.users.push({name: name});
                LayoutUserPanel.init();
                LayoutUserPanel.reset();
            }
        });
    },
            
    isNoUsers : function(){
        return (LayoutUserPanel.users.length === 1 && 
                LayoutUserPanel.users[0].name === "Please add users!");
    },
            
    setCurrentUserPoints: function(value) {
        this.usersPoints[this.current] = value;
    },
    nextUser: function() {
        var p = LayoutPointSelection.pointGet();
        if (!p)
            return;

        this.usersPoints[this.current] = p;

        var next = $("#panel .user[data='" + this.current + "']").next();
        if (next.attr("data")) {
            next.click();
        } else {
            $("#panel .result").click();
        }
    },
    reset: function() {
        this.usersPoints = {};
        $("#panel .user:first").click();
    }
};
